package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.FreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 陈辉
 * @data 2023 16:21
 */
@Service
public class FreemarkerServiceImpl implements FreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    /**
     * 生成文章详情页
     *
     * @param articleId
     * @param content
     */
    @Override
    @Async      //当前方法调用方式：线程池异步调用
    public void buildArticlePage(Long articleId, String content) {
        try {
            //1. 获取模板
            Template template = configuration.getTemplate("article.ftl");
            //2. 准备数据
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("content", JSONArray.parseArray(content));
            //3. 将数据填充到模板，生成详情页
            StringWriter writer = new StringWriter();
            template.process(dataMap,writer);
            //4. 将详情页数据上传到MinIO
            InputStream is = new ByteArrayInputStream(writer.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", articleId + ".html", is);

            //5. 将MinIO返回的url回填到ap_article表的static_url字段中
            ApArticle article  = new ApArticle();
            article.setId(articleId);
            article.setStaticUrl(path);
            apArticleMapper.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
